package com.rbac.admin.controller.system;

import com.rbac.admin.annotation.OperationLog;
import com.rbac.admin.common.result.Result;
import com.rbac.admin.dto.MenuDTO;
import com.rbac.admin.entity.system.SystemMenu;
import com.rbac.admin.service.system.MenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制器
 *
 * @author rbac-admin
 * @since 2024-07-19
 */
@Tag(name = "菜单管理", description = "菜单管理相关接口")
@RestController
@RequestMapping("/menus")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取所有菜单DTO列表（树形结构）
     */
    @Operation(summary = "获取所有菜单DTO列表（树形结构）")
    @OperationLog(module = "菜单管理", type = "查询", value = "查询菜单树结构")
    @GetMapping("/tree")
    public Result<List<MenuDTO>> getAllMenuDTOs(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String parentId) {
        try {
            System.out.println("查询参数: name=" + name + ", type=" + type + ", status=" + status + ", parentId=" + parentId);
            List<MenuDTO> menuDTOs = menuService.getAllMenuDTOs(name, type, status, parentId);
            System.out.println("获取菜单DTO(树形): " + menuDTOs);
            return Result.success(menuDTOs);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
    
    /**
     * 根据用户ID获取菜单DTO列表
     */
    @Operation(summary = "根据用户ID获取菜单DTO列表")
    @GetMapping("/user/{userId}/dto")
    public Result<List<MenuDTO>> getMenuDTOsByUserId(@PathVariable String userId) {
        try {
            List<MenuDTO> menuDTOs = menuService.getMenuDTOsByUserId(userId);
            System.out.println("转换后的菜单DTO数据：" + menuDTOs);
            return Result.success(menuDTOs);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
    
    /**
     * 根据角色ID获取菜单DTO列表
     */
    @Operation(summary = "根据角色ID获取菜单DTO列表")
    @GetMapping("/role/{roleId}/dto")
    public Result<List<MenuDTO>> getMenuDTOsByRoleId(@PathVariable String roleId) {
        try {
            List<MenuDTO> menuDTOs = menuService.getMenuDTOsByRoleId(roleId);
            return Result.success(menuDTOs);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
    
    /**
     * 根据角色ID获取菜单ID列表
     */
    @Operation(summary = "根据角色ID获取菜单ID列表")
    @GetMapping("/role/{roleId}/ids")
    public Result<List<String>> getMenuIdsByRoleId(@PathVariable String roleId) {
        try {
            List<String> menuIds = menuService.getMenuIdsByRoleId(roleId);
            return Result.success(menuIds);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 根据用户ID和角色ID获取菜单DTO列表（角色切换专用）
     */
    @Operation(summary = "根据用户ID和角色ID获取菜单DTO列表（角色切换专用）")
    @GetMapping("/user/{userId}/role/{roleId}/dto")
    public Result<List<MenuDTO>> getMenuDTOsByUserIdAndRoleId(@PathVariable String userId, @PathVariable String roleId) {
        try {
            List<MenuDTO> menuDTOs = menuService.getMenuDTOsByUserIdAndRoleId(userId, roleId);
            System.out.println("角色切换菜单查询：userId=" + userId + ", roleId=" + roleId + ", menuCount=" + menuDTOs.size());
            return Result.success(menuDTOs);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 获取菜单详情
     */
    @Operation(summary = "获取菜单详情")
    @OperationLog(module = "菜单管理", type = "查询", value = "查看菜单详情")
    @GetMapping("/{id}")
    public Result<SystemMenu> getMenuById(@PathVariable String id) {
        try {
            SystemMenu menu = menuService.getById(id);
            return Result.success(menu);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 创建菜单
     */
    @Operation(summary = "创建菜单")
    @OperationLog(module = "菜单管理", type = "新增", value = "新增菜单", recordParams = true, recordResult = true)
    @PostMapping
    public Result<SystemMenu> createMenu(@RequestBody SystemMenu menu) {
        try {
            menuService.save(menu);
            return Result.success("创建成功", menu);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 更新菜单
     */
    @Operation(summary = "更新菜单")
    @OperationLog(module = "菜单管理", type = "修改", value = "修改菜单信息", recordParams = true, recordResult = true)
    @PutMapping("/{id}")
    public Result<SystemMenu> updateMenu(@PathVariable String id, @RequestBody SystemMenu menu) {
        try {
            menu.setId(Integer.parseInt(id));
            menuService.updateById(menu);
            return Result.success("更新成功", menu);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 删除菜单
     */
    @Operation(summary = "删除菜单")
    @OperationLog(module = "菜单管理", type = "删除", value = "删除菜单", recordParams = true)
    @DeleteMapping("/{id}")
    public Result<Object> deleteMenu(@PathVariable String id) {
        try {
            menuService.removeById(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 批量删除菜单
     */
    @Operation(summary = "批量删除菜单")
    @OperationLog(module = "菜单管理", type = "删除", value = "批量删除菜单", recordParams = true)
    @DeleteMapping("/batch")
    public Result<Object> batchDeleteMenu(@RequestBody List<String> ids) {
        try {
            menuService.removeByIds(ids);
            return Result.success("批量删除成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 更新菜单排序
     */
    @Operation(summary = "更新菜单排序")
    @OperationLog(module = "菜单管理", type = "修改", value = "更新菜单排序", recordParams = true)
    @PutMapping("/sort")
    public Result<Object> updateMenuSort(@RequestBody List<SystemMenu> menus) {
        try {
            // 实际项目中，这里应该用批量更新或事务处理
            for (SystemMenu menu : menus) {
                SystemMenu dbMenu = menuService.getById(menu.getId());
                if (dbMenu != null) {
                    dbMenu.setSort(menu.getSort());
                    menuService.updateById(dbMenu);
                }
            }
            return Result.success("更新排序成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
} 